<template>
	<view>
		<scroll-view scroll-y="true">
			<uni-forms>
		<uni-card :is-shadow="false">
			<template v-slot:title>
				<view class="lig-card-title">
					<view class="uni-flex uni-row;" style="justify-content:space-between;">
						<view style="padding: 8rpx;">
							<text>发件信息</text>
						</view>
						<view>
							<switch-block
							          :switchList="pick_up_way.list"
							          v-model="pick_up_way.index"
							          :width="250"
							          :height="56"
									  @change="onChangePickup"
							        />
						</view>
					</view>
				</view>
			</template>
			<view class="uni-flex uni-row" style="justify-content:space-between;">
				<view class="uni-flex uni-column" style="flex-grow:2;">
					<navigator url="../address/address_fill?addressType=from">
					<view>
						<text>{{view.fromShopName}} {{view.fromAddress}}</text>
					</view>
					<view>
						<text style="font-size:24rpx;color:#bfbfbf;">{{view.fromLinkman}} {{view.fromPhone}}</text>
					</view>
					</navigator>
				</view>
				<navigator url="../address/address_choose?addressType=from">
					<view class="uni-flex uni-column"
						style="border-left: 2rpx solid #DDDDDD;padding:10rpx;align-items:center;width:80rpx;">
							<image style="width:40rpx;height:40rpx;" 
								src="../../static/image/address_book.png"></image>
							<view>
								<text style="font-size:24rpx;color:#7B7B7B;">地址薄</text>
							</view>
					</view>
				</navigator>
			</view>
		</uni-card>
		<uni-card :is-shadow="false">
			<template v-slot:title>
				<view class="lig-card-title">
					<view class="uni-flex uni-row" style="justify-content:space-between;">
						<view style="padding: 8rpx;">
							<text>收件信息</text>
						</view>
						<view>
							<switch-block
							          :switchList="deliver_way.list"
							          v-model="deliver_way.index"
							          :width="250"
							          :height="56"
									  @change="onChangeDeliverWay"
							        />
						</view>
					</view>
				</view>
				
			</template>
			<view class="uni-flex uni-row" style="justify-content:space-between;">
				<view class="uni-flex uni-column" style="flex-grow:2;">
					<navigator url="../address/address_fill?addressType=to">
						<view>
							<text>{{view.toShopName}} {{view.toAddress}}</text>
						</view>
						<view>
							<text style="font-size:24rpx;color:#bfbfbf;">{{view.toLinkman}} {{view.toPhone}}</text>
						</view>
					</navigator>
				</view>
				<navigator url="../address/address_choose?addressType=to">
					<view class="uni-flex uni-column"
						style="border-left: 2rpx solid #DDDDDD;padding:10rpx;align-items:center;width:80rpx;">
						
							<image style="width:40rpx;height:40rpx;" 
								src="../../static/image/address_book.png"></image>
							<view>
								<text style="font-size:24rpx;color:#7B7B7B;">地址薄</text>
							</view>
					</view>
				</navigator>
			</view>
		</uni-card>
		<!-- <view style="margin: 0 30rpx;">
		    <uni-segmented-control 
					:current="trans_way.index" 
					:values="trans_way.list" 
					@clickItem="onClickTransWay" 
					styleType="button" 
					activeColor="#FF4D4F"></uni-segmented-control>
		        
		</view> -->
		<uni-card :is-shadow="false" style="margin-top:0px;">
		<view class="content uni-bg-white">
		    <view v-show="trans_way.index == 0">
				<block v-for="(cargo, idx) in cargoList">
		        <view class="uni-flex uni-row trans_way_item" 
					v-for="(it, index) in cargo.spec" :key="index">
		        	<view class="uni-flex uni-row;" style="align-items:center;">
						<view>
							<text>{{it.name}}</text>
						</view>
						<view class="pref" v-show="it.promotion.onSale">{{it.promotion.desc}}</view>
					</view>
					<view>
						
					</view>
					<view>
						<uni-number-box :min="0" :max="99" :value="it.count" 
						v-model="it.count"
						@change="onChangeGoodsCount($event,idx,index)"/>
					</view>
		        </view>
				</block>
		    </view>
		    <view v-show="trans_way.index == 1">
		        <uni-forms-item label="协议价: " required>
					<uni-easyinput placeholder="0.00" 
						:type="digit" 
						v-model="order.agreementFee"
						@input="calcPrice2"/>
				</uni-forms-item>
		    </view>
		</view>
		</uni-card>
		<uni-card :is-shadow="false" padding="0" spacing="0">
			<uni-list :border="false">
				<uni-list-item title="可用优惠券" 
				rightText="无可用优惠券"></uni-list-item>
				<uni-list-item title="设为常发货源"
				:show-switch="true" :switchChecked="true"  
				@switchChange="switchChange" ></uni-list-item>
			</uni-list>
		</uni-card>
		<view style="padding:65rpx 0;">
			 
		</view>
		</uni-forms>
		</scroll-view>
	<view class="uni-flex uni-row uni-bg-white"
		style="position:fixed;bottom:0;width:100%;padding:20rpx 0;justify-content:space-between;z-index:999;">
		<view class="uni-flex uni-column" style="padding-left:20rpx;">
			<view style="margin-bottom:10px;font-size:32rpx;color:#FF4D4F;">预估价: ￥{{order.payFee}}</view>
			<view style="font-size:20rpx;color:#333333;">
				<checkbox-group @change="agreeChange">
					<checkbox :checked="state" style="transform:scale(0.7);" />阅读并同意《电子运单契约条款》
				</checkbox-group>
			</view>
			
		</view>
		<view style="width:260rpx;padding:12rpx 20rpx;">
			<button @click="onClickCreateOrder" v-if="!view.onAddOrder"
				style="background-color:#FF4D4F;color:#F8F8F8;font-size:32rpx;">下单</button>
			<button v-if="view.onAddOrder" disabled="true" style="font-size:12pt;">
				下单
			</button>
		</view>
	</view>
	<view>
		<!-- 提示窗示例 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog :type="dialog.msgType" cancelText="关闭" confirmText="知道了" title="提示" :content="dialog.content"></uni-popup-dialog>
		</uni-popup>
	</view>
	</view>
</template>

<script>
	import SwitchBlock from '@/components/liusheng22-switchBlock/liusheng22-switchBlock.vue';
	import { post, getUserId, getVersion, reLaunch2Index, checkLogin } from '@/util/request.js';
	import { wxPay } from '@/util/api.js';
	
	export default {
		components: {
		    SwitchBlock
		  },
		data() {
			return {
				version:'',
				pick_up_way: {
					list: ['上门取货', '自送'],
					index: 0
				},
				deliver_way: {
					list: ['送货上门', '自提'],
					index: 0
				},
				trans_way: {
				  list: ['拼车', '包车'],
				  index: 0
				}
				,shopBetween:{}
				,cargoList:[]
				,goodsList: []
				,view: {
					fromShopName: '',
					fromLinkman: '填写发件人',
					fromPhone: '',
					fromAddress: '填写详细地址',
					
					toShopName: '',
					toLinkman: '填写收件人',
					toPhone: '',
					toAddress: '填写详细地址',
					
					onAddOrder: false
				}
				,state: true
				,order: {
					fromTakeType: 1,
					fromShopId: '',
					fromShopName: '',
					fromLinkman: '',
					fromPhone: '',
					fromAddress: '',
					
					toTakeType: 1,
					toShopId: '',
					toShopName: '',
					toLinkman: '',
					toPhone: '',
					toAddress: '',
					
					transWay: 1,
					agreementFee: '0.00',
					payFee: '--',
					ifOften: 1,
					
					goodsList: [],
					
					openId: ''
				},
				dialog: {
					msgType: 'info',
					content: ''
				}
			}
		},
		onLoad(options) {
			this.checkLogin();
			
			this.getCargoList(options);
			
			wx.showShareMenu({
			    withShareTicket:true,
			    // 设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
			    menus:["shareAppMessage","shareTimeline"]
			});
		},
		onShow() {
			if (this.version != '' && this.version != getVersion()) {
				reLaunch2Index()
			} else {
				this.version = getVersion();
			}
			
			var that = this
			uni.$on('returnData',function(data){
				var books = data.books;
				if (typeof books == 'undefined') {
					return false;
				}
				
				if (books.addressType == 'from') {
					that.view.fromShopName = books.shopName;
					that.view.fromAddress = books.address;
					that.view.fromLinkman = books.linkman;
					that.view.fromPhone = books.phone;
					
					that.order.fromShopId = books.shopId;
					that.order.fromShopName = books.shopName;
					that.order.fromAddress = books.address;
					that.order.fromLinkman = books.linkman;
					that.order.fromPhone = books.phone;
				} else if (books.addressType == 'to') {
					that.view.toShopName = books.shopName;
					that.view.toAddress = books.address;
					that.view.toLinkman = books.linkman;
					that.view.toPhone = books.phone;
					
					that.order.toShopId = books.shopId;
					that.order.toShopName = books.shopName;
					that.order.toAddress = books.address;
					that.order.toLinkman = books.linkman;
					that.order.toPhone = books.phone;
				}
				that.switchCargoList();
				that.calcPrice();
			});
		},
		// 转发给好友
		onShareAppMessage(res) {
		    if (res.from === 'button') {// 来自页面内分享按钮
		    }
		    return {
		        title: APP_NAME //分享的名称
		    }
		},
		//分享到朋友圈
		onShareTimeline(res) {
		    return {
		        title: APP_NAME,
		        type: 0,
		        summary: "",
		    }
		},
		methods: {
			async checkLogin() {
				let res = await checkLogin();
				if (!res) {
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}
			},
			onClickTransWay(e) {
				if (this.trans_way.index != e.currentIndex) {
					this.trans_way.index = e.currentIndex;
				}
				
				if (e.currentIndex == 0) {
					this.order.transWay = 1;
					this.calcPrice();
				} else if (e.currentIndex == 1) {
					this.order.transWay = 2;
					this.calcPrice2();
				}
			}
			,onClickCreateOrder(e) {
				if (this.order.fromShopId == '') {
					uni.showToast({
						icon: 'none',
						title: '请填写发件信息'
					});
					return false;
				}
				if (this.order.toShopId == '') {
					uni.showToast({
						icon: 'none',
						title: '请填写收件信息'
					});
					return false;
				}
				
				if (this.order.transWay == 1) {
					//this.calcPrice();
					
					this.cargoList.forEach((cargo, idx) => {
						cargo.spec.forEach((it, index) => {
							if (it.count > 0) {
								this.order.goodsList.push({
									id: it.id,
									name: it.name,
									count: it.count,
									price: typeof cargo.union != 'undefined' && cargo.union.on ? cargo.union.price : it.price,
									cargoType: cargo.type
								});
							}
						});
					});
					
					if (this.order.goodsList.length <= 0) {
						uni.showToast({
							icon: 'none',
							title: '请填写拼车物件'
						});
						return false;
					}
				} else if (this.order.transWay == 2) {
					if (this.order.agreementFee == '' 
						|| this.order.agreementFee <= 0) {
						uni.showToast({
							icon: 'none',
							title: '请填写包车协议价'
						});
						return false;
					} else {
						//this.calcPrice2();
					}
				}
				
				if (!this.state) {
					uni.showToast({
						icon: 'none',
						title: '请阅读并勾选同意电子运单契约条款'
					});
					return false;
				}
				
				
				
				var userInfo = uni.getStorageSync('userInfo');
				if (userInfo != '' && userInfo.openId != '') {
					this.order.tenanId = userInfo.tenanId;
					this.order.openId = userInfo.openId;
					this.order.userId = userInfo.userId;
					
					// this.order.payFee = 0.01;
					wxPay('express/order/add', this.order);
					
					// uni.reLaunch({
					// 	url: '/pages/order/order_success'
					// });
				}
			}
			,onChangePickup(e) {
				this.order.fromTakeType = e.index == 0 ? 2 : 1;
				this.calcPrice();
			}
			,onChangeDeliverWay(e) {
				this.order.toTakeType = e.index == 0 ? 2: 1;
				this.calcPrice();
			}
			,onChangeGoodsCount(event, idx, index) {
				this.cargoList[idx].spec[index].count = event;
				// this.goodsList[index].count = event;
				this.calcPrice();
			}
			,calcPrice() {
				var that = this;
				if (that.order.fromShopId == '' 
					|| that.order.toShopId == '') {
					return false;
				}
				
				var _payFee = 0;
				var priceKey = that.order.fromShopId + '_' + that.order.toShopId;
				var _goodsList = [];
				that.cargoList.forEach((cargo, idx)=>{
					let fee = 0, 
						total = 0,
						deliFee = that.order.toTakeType == 1 ? cargo.deliFee : 0; // 派送费
					
					if (typeof cargo.union != 'undefined' && cargo.union.on) {
						cargo.spec.forEach((it, index) => {
							if (it.count > 0) {
								// 总数量
								total = total + it.count;
							}
						});
						// 货物价
						if (cargo.type == 1) {
							for (var i = 0; i < total; i++) {
								if (i <= 3) {
									fee = fee + cargo.union.price - (i * 10)
								} else {
									fee = fee + cargo.union.price - (3 * 10);
								}
							}
						} else if (cargo.type == 2) {
							fee = fee + (cargo.union.price * total);
						} else {
							fee = fee + (cargo.union.price * total);
						}
					} else {
						cargo.spec.forEach((it, index) => {
							let _price = it.price;
							if (it.count > 0) {
								// 总数量
								total = total + it.count;
								
								// 货物阶梯价
								if (cargo.type == 1) {
									for (var i = 0; i < it.count; i++) {
										if (i <= 3) {
											fee = fee + _price - (i * 10)
										} else {
											fee = fee + _price - (3 * 10);
										}
									}
									
								} else if (cargo.type == 2) {
									fee = fee + (_price * it.count);
								} else {
									fee = fee + (_price * it.count);
								}
								
								fee = that.calcPromotionPrice(fee, it.promotion);
								fee = that.order.fromTakeType == 1 ? fee : fee - it.takingFee;
							}
						});
					}
					
					// 优惠价
					if (total > 0) {
						let _fee = fee, 
							_basePrice = cargo.basePrice * total;
						if (_fee < _basePrice) {
							_fee = _basePrice;
						}
						
						_payFee = _payFee + _fee + (deliFee * total);
					}
				});
				// this.order.goodsList = _goodsList;
				this.order.payFee = _payFee;
			}
			,calcPrice2() {
				this.order.payFee = this.order.agreementFee;
			}
			,calcPromotionPrice(price, promotion) {
				if (promotion && promotion.onSale && price >= promotion.threshold) {
					if (promotion.type == 1) {
						// 满折
						return price * promotion.discount;
					} else if (promotion.type == 2) {
						// 满减
						if (price >= promotion.reduction) {
							return price - promotion.reduction;
						}
					}
				}
				return price;
			}
			,getCargoList(options) {
				let userId = getUserId();
				if (userId == null || userId == '') {
					return;
				}
				post('express/cargo/list/v2', {
					userId: userId
				}).then(res => {
					this.shopBetween = res.data;
					
					if (typeof options.again == 'undefined') {
						this.fillCargoList('basic', {});
					} else {
						this.initAgain(options.again);
					}
					
					// this.goodsList = _goodsList;
					//this.initAgain(options.again);
				});
			}
			,switchCargoList() {
				var that = this;
				if (that.order.fromShopId == '' 
					|| that.order.toShopId == '') {
					return false;
				}
				
				var specCount = {};
				this.cargoList.forEach((cargo, idx) => {
					cargo.spec.forEach((it, index) => {
						specCount[it.id] = it.count;
					});
				});
				that.fillCargoList(that.order.fromShopId + "_" + that.order.toShopId, specCount);
			}
			,fillCargoList(key, specCount) {
				if (typeof this.shopBetween[key] == 'undefined') {
					this.dialog = {
						msgType: 'warn',
						content: this.order.fromShopName + '-' + this.order.toShopName + ", 该线路尚未服务, 请重新选择"
					}
					this.$refs.alertDialog.open();
					this.view.onAddOrder = true;
				} else {
					this.view.onAddOrder = false;
					this.cargoList = this.shopBetween[key].cargo;
					this.cargoList.forEach((cargo, idx) => {
						cargo.spec.forEach((it, index) => {
							it.count = typeof specCount[it.id] == 'undefined' ? 0 : specCount[it.id];
							if (!it.promotion || !it.promotion.onSale) {
								it.promotion = cargo.promotion;
							}
						});
					});
				}
			}
			,agreeChange(e) {
				this.state = !this.state;
			},
			switchChange(e) {
				if (e.value) {
					this.order.ifOften = 1;
				} else {
					this.order.ifOften = 0;
				}
			}
			,initAgain(content) {
				let again = JSON.parse(decodeURIComponent(content));

				this.view.fromShopName = again.fromShopName;
				this.view.fromAddress = again.fromAddress;
				this.view.fromLinkman = again.fromLinkman;
				this.view.fromPhone = again.fromPhone;
				
				this.view.toShopName = again.toShopName;
				this.view.toAddress = again.toAddress;
				this.view.toLinkman = again.toLinkman;
				this.view.toPhone = again.toPhone;
				
				// this.order.fromTakeType = again.fromTakeType == 2 ? 1 : 0;
				this.order.fromTakeType = 1;
				this.order.fromShopId = again.fromShopId;
				this.order.fromShopName = again.fromShopName;
				this.order.fromAddress = again.fromAddress;
				this.order.fromLinkman = again.fromLinkman;
				this.order.fromPhone = again.fromPhone;
				
				//this.order.toTakeType = again.toTakeType == 2 ? 1 : 0;
				this.order.toTakeType = 1;
				this.order.toShopId = again.toShopId;
				this.order.toShopName = again.toShopName;
				this.order.toAddress = again.toAddress;
				this.order.toLinkman = again.toLinkman;
				this.order.toPhone = again.toPhone;
				
				this.pick_up_way.index = 0 ;
				this.deliver_way.index = 0;
				
				if (this.order.fromShopId == '' 
					|| this.order.toShopId == '') {
					return false;
				}
				
				if (again.goodsList && again.goodsList.length > 0) {
					var specCount = {};
					// again.goodsList.forEach((it, index) => {
					// 	specCount[it.id] = it.count;
					// });
					this.fillCargoList(this.order.fromShopId + "_" + this.order.toShopId, specCount);
					this.calcPrice();
				}
			}
		}
	}
</script>

<style>
.trans_way_item {
	padding:14rpx 10rpx;
	border-bottom: 2rpx solid #f5f5f5;
	justify-content:space-between;
	font-size:11pt;
}
.pref {
	font-size: 7pt;
	color: #FFF;
	background-color: #FF4D4F;
	border: 0px;
	border-radius: 40rpx;
	padding: 1rpx 4rpx;
	margin: 0px 20rpx;
	text-align: center;
	display: flex;
	align-items: center;
	height: 38rpx;
}
.uni-numbox-btns.data-v-dd94a2a8 {}
</style>
